﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Missbot.Common;
using Missbot.Service;
using MongoDB.Driver;

namespace MissRobot.Migrator.SourceMongo
{
    public class SourceMongoService<T> where T : DbBaseEntity
    {
        private static SourceMongContext Repo => AutofacSvc.Resolve<SourceMongContext>();

        /// <summary>
        /// 获取集合（表）
        /// </summary>
        /// <returns></returns>
        public static IMongoCollection<T> GetCollection()
        {
            return Repo.Collection<T>();
        }

        /// <summary>
        /// 强类型查询（适用精确查询）
        /// 查询条件包含可为空的时间类型字段时：只能查询有无值
        /// </summary>
        /// <param name="exp"></param>
        /// <returns></returns>
        public static List<T> Get(Expression<Func<T, bool>> exp)
        {
            return GetCollection().Find(exp).ToList();
        }

        public static List<T> Get(Expression<Func<T, bool>> findExp, Expression<Func<T, object>> sortExp, bool isAscending = true, int skip = 0, int limit = 0)
        {
            var fluent = GetCollection().Find(findExp);

            var sortBuilder = Builders<T>.Sort;
            var sortDef     = isAscending ? sortBuilder.Ascending(sortExp) : sortBuilder.Descending(sortExp);
            fluent = fluent.Sort(sortDef);

            if (skip != 0)
            {
                fluent = fluent.Skip(skip);
            }

            if (limit != 0)
            {
                fluent = fluent.Limit(limit);
            }

            return fluent.ToList();
        }

        public static List<T> Get()
        {
            return Get(p => true);
        }

        public static T GetOnly(Expression<Func<T, bool>> exp)
        {
            return Get(exp).FirstOrDefault();
        }
    }
}